
<template>
    <div class="h-full flex-1 flex flex-col p-6 overflow-auto">
      <!-- 智能Agent数字人区域 -->
      <div class="mb-4 flex-shrink-0">
        <DigitalHuman ref="digitalHuman" :enable-auto-broadcast="true"
          @broadcast-complete="onBroadcastComplete" @user-interaction="onUserInteraction" class="mb-3" />
  
        <!-- 智能Agent状态栏 -->
        <div class="glass-card p-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <div class="flex items-center space-x-2">
                <div class="relative">
                  <div :class="[
                    'w-3 h-3 rounded-full',
                    agentStatus === 'active' ? 'bg-green-400 animate-pulse' :
                      agentStatus === 'thinking' ? 'bg-yellow-400 animate-pulse' : 'bg-gray-400'
                  ]"></div>
                  <div v-if="agentStatus === 'active'"
                    class="absolute inset-0 w-3 h-3 rounded-full bg-green-400 animate-ping opacity-75"></div>
                </div>
                <span class="font-medium" :class="themeState.isLight ? 'text-gray-900' : 'text-white'">
                  🤖 {{ ts('智能Agent代理') }}
                  <span class="text-electric-500 ml-1">
                    {{ agentStatus === 'active' ? ts('活跃中') :
                      agentStatus === 'thinking' ? ts('思考中') : ts('待机中') }}
                  </span>
                </span>
              </div>
  
              <div class="flex items-center space-x-4 text-sm">
                <div :class="themeState.isLight ? 'text-gray-600' : 'text-white/70'">
                  <span class="text-electric-500">{{ todayRecommendations }}</span> {{ ts('今日推荐') }}
                </div>
                <div :class="themeState.isLight ? 'text-gray-600' : 'text-white/70'">
                  <span class="text-electric-500">{{ activeNotifications }}</span> {{ ts('活跃推送') }}
                </div>
                <div :class="themeState.isLight ? 'text-gray-600' : 'text-white/70'">
                  <span class="text-electric-500">{{ policyMatches }}</span> {{ ts('政策匹配') }}
                </div>
              </div>
            </div>
  
            <div class="flex items-center space-x-2">
              <button @click="toggleAgentMode" :class="[
                'px-3 py-1 rounded-full text-xs font-medium transition-all',
                smartMode ? 'bg-electric-500 text-white' : 'bg-white/10 text-white/70 hover:bg-white/20'
              ]">
                {{ smartMode ? ts('🧠 智能模式') : ts('💬 普通模式') }}
              </button>
              <button @click="triggerSmartAnalysis"
                class="px-3 py-1 rounded-full text-xs font-medium bg-tech-blue-500 text-white hover:bg-tech-blue-600 transition-all">
                {{ ts('🎯 智能分析') }}
              </button>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 数字人控制面板 -->
      <div class="glass-card p-4 mb-6">
        <h3 class="text-lg font-semibold text-white mb-3">{{ ts('数字人控制') }}</h3>
        <div class="grid grid-cols-3 gap-4">
          <button @click="triggerWelcome" class="cyber-button py-2">
            {{ ts('欢迎播报') }}
          </button>
          <button @click="triggerPolicyUpdate" class="cyber-button py-2">
            {{ ts('政策更新') }}
          </button>
          <button @click="triggerAnalysisReport" class="cyber-button py-2">
            {{ ts('分析报告') }}
          </button>
        </div>
      </div>
  
      <!-- Agent活动监控 -->
      <div class="glass-card p-4 flex-1">
        <h3 class="text-lg font-semibold text-white mb-3">{{ ts('Agent活动监控') }}</h3>
        <div class="space-y-4">
          <!-- 实时活动 -->
          <div class="bg-white/5 rounded-lg p-3">
            <div class="flex items-center justify-between mb-2">
              <span class="text-white text-sm">{{ ts('实时活动') }}</span>
              <div :class="[
                'w-2 h-2 rounded-full',
                agentStatus === 'active' ? 'bg-green-400 animate-pulse' :
                  agentStatus === 'thinking' ? 'bg-yellow-400 animate-pulse' : 'bg-gray-400'
              ]"></div>
            </div>
            <div class="text-electric-500 text-xs">
              {{ agentStatus === 'active' ? ts('正在监控政策更新') :
                agentStatus === 'thinking' ? ts('正在分析用户意图') : ts('待机中') }}
            </div>
          </div>
  
          <!-- 今日统计 -->
          <div class="grid grid-cols-3 gap-2">
            <div class="bg-white/5 rounded-lg p-2 text-center">
              <div class="text-electric-500 text-lg font-bold">{{ todayRecommendations }}</div>
              <div class="text-white/70 text-xs">{{ ts('智能推荐') }}</div>
            </div>
            <div class="bg-white/5 rounded-lg p-2 text-center">
              <div class="text-electric-500 text-lg font-bold">{{ policyMatches }}</div>
              <div class="text-white/70 text-xs">{{ ts('政策匹配') }}</div>
            </div>
            <div class="bg-white/5 rounded-lg p-2 text-center">
              <div class="text-electric-500 text-lg font-bold">{{ activeNotifications }}</div>
              <div class="text-white/70 text-xs">{{ ts('活跃推送') }}</div>
            </div>
          </div>
  
          <!-- 最近动作 -->
          <div class="bg-white/5 rounded-lg p-3">
            <div class="text-white text-sm mb-2">{{ ts('最近动作') }}</div>
            <div class="space-y-1">
              <div v-for="(action, index) in recentActions" :key="index"
                class="flex items-center justify-between text-xs">
                <span class="text-white/70">{{ action.action }}</span>
                <span class="text-electric-500">{{ action.time }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { useTranslation } from '../composables/useTranslation.js'
  import { themeState } from '../services/themeService.js'
  import DigitalHuman from '../components/DigitalHuman.vue'
  import { IntelligentAgent } from '../services/intelligentAgent.js'
  
  export default {
    name: 'DigitalHumanPage',
    components: {
      DigitalHuman
    },
    setup() {
      const { ts } = useTranslation()
      return {
        ts,
        themeState
      }
    },
    data() {
      return {
        // 智能Agent相关数据
        intelligentAgent: null,
        agentStatus: 'active', // active, thinking, idle
        smartMode: true, // 默认开启智能模式
        todayRecommendations: 8,
        activeNotifications: 3,
        policyMatches: 15,
        recentActions: [
          { action: '分析用户意图', time: '2分钟前' },
          { action: '推荐政策匹配', time: '5分钟前' },
          { action: '生成智能回复', time: '8分钟前' },
          { action: '监控政策更新', time: '10分钟前' }
        ]
      }
    },
    methods: {
      // 数字人控制方法
      triggerWelcome() {
        this.$refs.digitalHuman?.triggerBroadcast({
          message: '您好！欢迎使用智能政策咨询系统，我是您的数字人助手，可以为您解答各类政策问题并提供个性化建议。',
          type: 'welcome',
          urgency: 'normal'
        })
        this.addRecentAction('触发欢迎播报')
      },
      
      triggerPolicyUpdate() {
        this.$refs.digitalHuman?.triggerBroadcast({
          message: '最新政策通知：关于支持高新技术企业发展的若干措施已于2024年1月15日正式实施，主要内容包括税收减免、研发补贴等优惠政策。',
          type: 'notification',
          urgency: 'high'
        })
        this.addRecentAction('播报政策更新')
      },
      
      triggerAnalysisReport() {
        this.$refs.digitalHuman?.triggerBroadcast({
          message: '根据近期咨询数据分析，企业最关注的是数字化转型补贴和出口认证政策，建议重点关注相关领域的最新动态。',
          type: 'analysis',
          urgency: 'normal'
        })
        this.addRecentAction('生成分析报告')
      },
      
      // 智能Agent相关方法
      async initializeIntelligentAgent() {
        try {
          this.intelligentAgent = new IntelligentAgent()
          await this.intelligentAgent.initialize()
  
          // 设置事件监听
          this.intelligentAgent.addEventListener('recommendation', this.handleRecommendation)
          this.intelligentAgent.addEventListener('notification', this.handleNotification)
          this.intelligentAgent.addEventListener('analysis', this.handleAnalysis)
  
          this.agentStatus = 'active'
          this.updateAgentStats()
          this.addRecentAction('智能Agent代理启动')
  
        } catch (error) {
          console.error('智能Agent初始化失败:', error)
          this.agentStatus = 'idle'
        }
      },
  
      handleRecommendation(data) {
        this.todayRecommendations += data.recommendations?.length || 1
        this.addRecentAction('生成智能推荐')
      },
  
      handleNotification(data) {
        this.activeNotifications += 1
        this.addRecentAction('发送通知')
      },
  
      handleAnalysis(data) {
        this.policyMatches += data.matches?.length || 1
        this.addRecentAction('完成政策分析')
      },
  
      toggleAgentMode() {
        this.smartMode = !this.smartMode
        this.addRecentAction(`切换到${this.smartMode ? '智能' : '普通'}模式`)
      },
  
      async triggerSmartAnalysis() {
        if (!this.intelligentAgent) return
  
        this.agentStatus = 'thinking'
        this.addRecentAction('执行智能分析')
  
        try {
          const analysis = await this.intelligentAgent.analyzeGlobalData()
          this.policyMatches += analysis.matches?.length || 3
          this.todayRecommendations += analysis.recommendations?.length || 2
          
          this.agentStatus = 'active'
          this.addRecentAction('完成全局分析')
          
        } catch (error) {
          console.error('智能分析失败:', error)
          this.agentStatus = 'active'
        }
      },
  
      updateAgentStats() {
        if (this.intelligentAgent) {
          const stats = this.intelligentAgent.getStatistics()
          this.todayRecommendations = stats.totalRecommendations || this.todayRecommendations
          this.activeNotifications = stats.activeNotifications || this.activeNotifications
          this.policyMatches = stats.policyMatches || this.policyMatches
        }
      },
  
      onBroadcastComplete(data) {
        console.log('播报完成:', data)
      },
  
      onUserInteraction(data) {
        console.log('用户交互:', data)
      },
  
      addRecentAction(action) {
        const newAction = {
          action,
          time: '刚刚'
        }
  
        this.recentActions.unshift(newAction)
        if (this.recentActions.length > 4) {
          this.recentActions.pop()
        }
  
        setTimeout(() => {
          this.updateActionTimes()
        }, 60000)
      },
  
      updateActionTimes() {
        this.recentActions = this.recentActions.map((action, index) => ({
          ...action,
          time: `${index + 1}分钟前`
        }))
      }
    },
  
    async mounted() {
      await this.initializeIntelligentAgent()
  
      setInterval(() => {
        this.updateAgentStats()
      }, 30000)
  
      setInterval(() => {
        this.updateActionTimes()
      }, 60000)
  
      setInterval(() => {
        if (this.agentStatus === 'active' && Math.random() > 0.7) {
          const activities = ['监控政策更新', '扫描市场动态', '更新知识库', '优化推荐算法']
          const activity = activities[Math.floor(Math.random() * activities.length)]
          this.addRecentAction(activity)
        }
      }, 120000)
    },
  
    beforeUnmount() {
      if (this.intelligentAgent) {
        this.intelligentAgent.destroy()
      }
    }
  }
  </script>
  
  <style scoped>
  .glass-card {
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
  }
  
  .cyber-button {
    background: linear-gradient(135deg, #6e8efb, #a777e3);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
  }
  
  .cyber-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(167, 119, 227, 0.4);
  }
  </style>